package com.cade.agriculturemall.view.classify;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.cade.agriculturemall.R;
import com.cade.agriculturemall.base.BaseAdapter;
import com.cade.agriculturemall.model.GoodsDetailEntity;
import com.cade.agriculturemall.model.GoodsItemEntity;
import com.cade.agriculturemall.utils.RefreshLayout;
import com.cade.agriculturemall.view.classify.goodsdetail.GoodsDetailActivity;
import com.cade.agriculturemall.view.refresh.OnRefreshListener;
import com.cade.agriculturemall.widget.EmptyLayout;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Lobby on 2017/11/20.
 * ClassifyNewFrameLayout：itemlist 相关
 */

public class ClassifyNewFrameLayout extends FrameLayout {


    private TabLayout mTabLayout;
    private Button mBtn;
    private ViewPager mViewPager;
    private PopupWindow popupWindow;
    private boolean isPopupWindowShowing = false;
    private RecyclerView rv_pop;
    private ChannelAdapter adapter;
    private List<String> alterChannels = new ArrayList<>();
    private FragmentManager childFragmentManager;

    public ClassifyNewFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.activity_classfity_new_fragment, this, true);
        mTabLayout = (TabLayout) findViewById(R.id.tab);
        mBtn = (Button) findViewById(R.id.btn_tab_select);
        mViewPager = (ViewPager) findViewById(R.id.vp_news_main);
        initData();
        loadCommonData();
    }

    private void loadCommonData() {

    }

    // 获取itemList数据
    public void getGoodsItemList() {
        final AVQuery<GoodsItemEntity> query = new AVQuery<>("ClassifyGoodsSecond");
//        avQuery.orderByDescending("createAt");
        query.selectKeys(Arrays.asList("category_name"));
        query.findInBackground(new FindCallback<GoodsItemEntity>() {
            @Override
            public void done(List<GoodsItemEntity> list, AVException e) {
                pageTitles.clear();
                pageFragments.clear();
                int type = 0;
                if(list.size()!=0)
                for (GoodsItemEntity avObject : list) {
//                    ModelUtil.initObject(avObject);
                    String item = avObject.getTitle();
                    String objectId = avObject.getObjectId();
                    pageTitles.add(item);
                    pageFragments.add(PageListFragment.newInstance(objectId));
                    type++;
                }
                init();
                if (mPageAdapter != null) {
                    mPageAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void initData() {

    }

    private void init() {
        if (pageTitles.size() < 5)
            mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        else
            mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
// 点击按钮显示更多，弹出popwindows
        mBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                View popView = LayoutInflater.from(getContext()).inflate(R.layout.layout_popupwindow_selecttab, null);

                rv_pop = (RecyclerView) popView.findViewById(R.id.rv_popup);
                GridLayoutManager manager = new GridLayoutManager(getContext(), 4);
                rv_pop.setLayoutManager(manager);

                ItemDragHelperCallback cb = new ItemDragHelperCallback();
                ItemTouchHelper helper = new ItemTouchHelper(cb);
                helper.attachToRecyclerView(rv_pop);

                Button btn_popup = (Button) popView.findViewById(R.id.btn_popup);
                TextView tv_popup = (TextView) popView.findViewById(R.id.tv_popup);
                popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);

                adapter = new ChannelAdapter(getContext(), helper, pageTitles, alterChannels, btn_popup, tv_popup);
                btn_popup.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!adapter.getIsEditMode()) {
                            refreshUI();
                        } else {
                            adapter.cancelEditMode(rv_pop);
                        }
                    }
                });
                manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int position) {
                        int viewType = adapter.getItemViewType(position);
                        return viewType == ChannelAdapter.TYPE_OTHER_CHANNEL_HEADER ? 4 : 1;
                    }
                });

                rv_pop.setAdapter(adapter);
                adapter.setOnMyChannelItemClickListener(new ChannelAdapter.OnMyChannelItemClickListener() {
                    @Override
                    public void onItemClick(View v, int position) {
                        refreshUI();
                        int currPos = mTabLayout.getSelectedTabPosition();
                        if (currPos != position) {
                            mTabLayout.setScrollPosition(currPos, position - currPos, true);
                            mViewPager.setCurrentItem(position);
                        }
                    }
                });

                popupWindow.setBackgroundDrawable(null);
                popupWindow.setFocusable(false);
                popupWindow.showAsDropDown(mBtn, 0, -mBtn.getHeight());
                isPopupWindowShowing = true;
            }
        });
    }


    public boolean getIsPopupWindowShowing() {
        return isPopupWindowShowing;
    }

    public void onBackPressed() {
        if (popupWindow != null) {
            if (popupWindow.isShowing()) {
                if (adapter.getIsEditMode()) {
                    adapter.cancelEditMode(rv_pop);
                    return;
                }
                refreshUI();
            }
        }
    }


    private void refreshUI() {
        pageTitles = adapter.getmMyChannelItems();
        alterChannels = adapter.getmOtherChannelItems();
        SharedPreferences.Editor editor = getContext().getSharedPreferences("tabStringList", Context.MODE_PRIVATE).edit();

        editor.apply();
//        vpAdapter.setTabs(myChannels);
//        if (myChannels.size() < 5)
//            mTabLayout.setTabMode(TabLayout.MODE_FIXED);
//        else
        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
//        vpAdapter.notifyDataSetChanged();
        popupWindow.dismiss();
        isPopupWindowShowing = false;
    }


    private ChildPageAdapter mPageAdapter;

    public void setChildFragmentManager(FragmentManager childFragmentManager) {
        this.childFragmentManager = childFragmentManager;
        mPageAdapter = new ChildPageAdapter(childFragmentManager);
        mViewPager.setAdapter(mPageAdapter);
        mTabLayout.setupWithViewPager(mViewPager);


    }

    //      ViewPager
    private List<String> pageTitles = new ArrayList<>();
    private List<Fragment> pageFragments = new ArrayList<>();

    //      底部商品展示 FragmentPagerAdapter
    private class ChildPageAdapter extends FragmentPagerAdapter {


        public ChildPageAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return pageTitles.size();
        }


        @Override
        public CharSequence getPageTitle(int position) {
            return pageTitles.get(position);
        }

        @Override
        public Fragment getItem(int position) {
            return pageFragments.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {

        }

        @Override
        public void destroyItem(View container, int position, Object object) {

        }
    }


    //    商品展示
    public static class PageListFragment extends Fragment implements OnRefreshListener {
        private String parentId = "";
        private RecyclerView mRecyclerView;

        private EmptyLayout mEmptyLayout;

        public static PageListFragment newInstance(String objectId) {

            Bundle args = new Bundle();
            args.putString("objectId", objectId);
            PageListFragment fragment = new PageListFragment();
            fragment.setArguments(args);
            return fragment;
        }


        private PageListFragmentAdapter mPageListFragmentAdapter;
        private List<GoodsDetailEntity> mGoodsDetailEntityList = new ArrayList<>();
        private RefreshLayout refreshLayout ;

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            parentId = getArguments().getString("objectId");
            initData(parentId);
            View view = inflater.inflate(R.layout.fragment_page_list, container, false);
            return view;
        }

        public void initData(String parentId) {
            AVQuery<GoodsDetailEntity> avQuery = new AVQuery<>("ClassifyGoodsThird");
            avQuery.whereEqualTo("parentId", parentId);
            avQuery.orderByDescending("sell_offs");
            avQuery.findInBackground(new FindCallback<GoodsDetailEntity>() {
                @Override
                public void done(List<GoodsDetailEntity> list, AVException e) {
                    if (list.size() != 0) {
                        mEmptyLayout.reset();
                        mGoodsDetailEntityList = list;
                        mPageListFragmentAdapter.setList(mGoodsDetailEntityList);
                        mPageListFragmentAdapter.notifyDataSetChanged();

                    } else {
                        mEmptyLayout.empty();
                    }
                }
            });
        }

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
//            refreshLayout= (RefreshLayout) getView().findViewById(R.id.fragment_page_item_refresh);
//            refreshLayout.setOnRefreshListener(this);
//            refreshLayout.setLoadMoreEnable(false);
            mEmptyLayout = (EmptyLayout) getView().findViewById(R.id.fragment_page_item_emptylayout);
            mPageListFragmentAdapter = new PageListFragmentAdapter(getParentFragment().getActivity());
            mRecyclerView = (RecyclerView) getView().findViewById(R.id.fragment_page_item_recyclerview);
            mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
            mRecyclerView.setAdapter(mPageListFragmentAdapter);
            mPageListFragmentAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    onItemClickEvent(position);
                }
            });
            mEmptyLayout.setOnEmptyLayoutListener(new EmptyLayout.OnEmptyLayoutListener() {
                @Override
                public boolean onReloadClick(@NotNull EmptyLayout layout) {
                    initData(parentId);
                    return true;
                }
            });
        }

        private void onItemClickEvent(int position) {
            GoodsDetailEntity mEntity = mGoodsDetailEntityList.get(position);
            if (mEntity.getObjectId() != null) {
                Intent intent = new Intent(getParentFragment().getActivity(), GoodsDetailActivity.class);
                intent.putExtra("objectId", mEntity.getObjectId());
                startActivity(intent);
            }
        }

        @Override
        public void onStartRefresh() {
            initData(parentId);
            refreshLayout.endRefreshing();
        }
    }
}
